//
//  FlowListVC.swift
//  Employee
//
//  Created by swordjoy on 2017/6/28.
//  Copyright © 2017年 remotevillage. All rights reserved.
//

import UIKit
import Moya
import MJRefresh

enum FlowListVCType {
  case apply
  case check
  case copy
  case home
}

class FlowListVC: BaseVC {

    var type: FlowListVCType!
    var parentVC: BaseVC!

    fileprivate var pager = PageModel()
    fileprivate var models: [FlowList] = []
    fileprivate var sendModel = FlowListSend()
  
    fileprivate var tableView: UITableView?
    fileprivate var refreshFooter: MJRefreshFooter!
    fileprivate var cancle: Cancellable?
  
    override func viewDidLoad() {
        super.viewDidLoad()
        create()
    }
  
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
    
    deinit {
        cancle?.cancel()
    }


}

extension FlowListVC {
  
  func updateData() {
    cancle = FlowRequest.shared.myCheck(page: pager.headerPage, success: { (datas, page) in
      self.models = datas
      self.pager = page
      runOnMainThread {
        self.tableView?.mj_header.endRefreshing()
        if page.hasData {
            self.tableView?.mj_footer.isHidden = false
            if page.hasNextPage { self.tableView?.mj_footer.endRefreshing() }
            else { self.tableView?.mj_footer.endRefreshingWithNoMoreData() }
        }
        else { self.tableView?.mj_footer.isHidden = true }
        self.tableView?.reloadData()
      }
    }, failure: {
      self.tableView?.mj_header.endRefreshing()
    })
  }
  
  func pullData(with searchKey: FlowListSend) {
    sendModel.status = searchKey.status
    sendModel.flowId = searchKey.flowId
    sendModel.page = pager.headerPage
    if .apply == type {
      cancle = FlowRequest.shared.getApplyList(model: sendModel, success: { (datas, page) in
        self.models = datas
        self.pager = page
        runOnMainThread {
          self.tableView?.mj_header.endRefreshing()
            if page.hasData {
                self.tableView?.mj_footer.isHidden = false
                if page.hasNextPage {
                    self.tableView?.mj_footer.endRefreshing()
                }
                else {
                    self.tableView?.mj_footer.endRefreshingWithNoMoreData()
                }
            }
            else { self.tableView?.mj_footer.isHidden = true }
            
            self.tableView?.reloadData()
        }
      }, failure: { 
        self.tableView?.mj_header.endRefreshing()
      })
    }
    else if .check == type {
        if "Revoked" == sendModel.status { sendModel.status = "" }
      cancle = FlowRequest.shared.getCheckList(model: sendModel, success: { (datas, page) in
        self.models = datas
        self.pager = page
        runOnMainThread {
          self.tableView?.mj_header.endRefreshing()
            if page.hasData {
                self.tableView?.mj_footer.isHidden = false
                if page.hasNextPage { self.tableView?.mj_footer.endRefreshing() }
                else { self.tableView?.mj_footer.endRefreshingWithNoMoreData() }
            }
            else { self.tableView?.mj_footer.isHidden = true }
          self.tableView?.reloadData()
        }
      }, failure: {
        self.tableView?.mj_header.endRefreshing()
      })
    }
    else if .copy == type {
        if "Revoked" == sendModel.status { sendModel.status = "" }
      cancle = FlowRequest.shared.getCopyList(model: sendModel, success: { (datas, page) in
        self.models = datas
        self.pager = page
        runOnMainThread {
          self.tableView?.mj_header.endRefreshing()
            if page.hasData {
                self.tableView?.mj_footer.isHidden = false
                if page.hasNextPage { self.tableView?.mj_footer.endRefreshing() }
                else { self.tableView?.mj_footer.endRefreshingWithNoMoreData() }
            }
            else { self.tableView?.mj_footer.isHidden = true }
          self.tableView?.reloadData()
        }
      }, failure: {
        self.tableView?.mj_header.endRefreshing()
      })
    }
  }
  
  func headerRefresh() {
    self.pullData(with: sendModel)
  }
  
  func footerRefresh() {
    sendModel.page = pager.nextPage
    if .apply == type {
      cancle = FlowRequest.shared.getApplyList(model: sendModel, success: { (datas, page) in
        self.models += datas
        self.pager = page
        runOnMainThread {
          self.tableView?.reloadData()
          if page.hasNextPage { self.tableView?.mj_footer.endRefreshing() }
          else { self.tableView?.mj_footer.endRefreshingWithNoMoreData() }
        }
      }, failure: {
        self.tableView?.mj_footer.endRefreshing()
      })
    }
    else if .check == type {
      cancle = FlowRequest.shared.getCheckList(model: sendModel, success: { (datas, page) in
        self.models += datas
        self.pager = page
        runOnMainThread {
          self.tableView?.reloadData()
          if page.hasNextPage { self.tableView?.mj_footer.endRefreshing() }
          else { self.tableView?.mj_footer.endRefreshingWithNoMoreData() }
        }
      }, failure: {
        self.tableView?.mj_footer.endRefreshing()
      })
    }
    else if .copy == type {
      cancle = FlowRequest.shared.getCopyList(model: sendModel, success: { (datas, page) in
        self.models += datas
        self.pager = page
        runOnMainThread {
          self.tableView?.reloadData()
          if page.hasNextPage { self.tableView?.mj_footer.endRefreshing() }
          else { self.tableView?.mj_footer.endRefreshingWithNoMoreData() }
        }
      }, failure: {
        self.tableView?.mj_footer.endRefreshing()
      })
    }
    else if .home == type {
      cancle = FlowRequest.shared.myCheck(page: pager.headerPage, success: { (datas, page) in
        self.models += datas
        self.pager = page
        runOnMainThread {
          self.tableView?.reloadData()
          if page.hasNextPage { self.tableView?.mj_footer.endRefreshing() }
          else { self.tableView?.mj_footer.endRefreshingWithNoMoreData() }
        }
      }, failure: {
        self.tableView?.mj_footer.endRefreshing()
      })
    }
  }
}

// MARK: - UITableViewDelegate

extension FlowListVC: UITableViewDelegate {
  func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return FlowListCell.height(with: models[indexPath.row])
  }
  
  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let vc = FlowDetailVC()
    vc.flowId = models[indexPath.row].id
    if .apply == type {
        vc.type = .apply
        
    }
    else if .check == type {
        vc.type = .check
        vc.refreshBefore = { self.updateData() }
    }
    else if .copy == type { vc.type = .copy }
    else if .home == type {
        vc.refreshBefore = { self.updateData() }
      vc.type = .home
    }
    
    parentVC.navigationController?.pushViewController(vc, animated: true)
  }
}

// MARK: - UITableViewDataSource

extension FlowListVC: UITableViewDataSource {
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return models.count
  }
  
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: FlowListCell.identifier) as! FlowListCell
    
    if .home == type || .check == type { cell.checkModel = models[indexPath.row] }
    else { cell.model = models[indexPath.row] }
    
    return cell
  }
}

// MARK: - fileprivate

extension FlowListVC {
  
  fileprivate func create() {
    view.backgroundColor = GlobalConfig.BGWhiteColor
    
    tableView = UITableView()
    tableView?.backgroundColor = GlobalConfig.BGWhiteColor
    tableView?.delegate = self
    
    if .home == type {
      tableView?.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
      tableView?.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.noBarHeight - 44)
      let headerView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 4))
      headerView.backgroundColor = GlobalConfig.BGWhiteColor
      tableView?.tableHeaderView = headerView
      sendModel.status = "Auditing"
      sendModel.page = pager.headerPage
      tableView?.mj_header = CustomRefreshHeader(refreshingTarget: self, refreshingAction: #selector(updateData))
    }
    else {
      tableView?.contentInset = UIEdgeInsets(top: 44 + 5, left: 0, bottom: 0, right: 0)
      tableView?.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.noNavBarHeight - 44)
      tableView?.mj_header = CustomRefreshHeader(refreshingTarget: self, refreshingAction: #selector(headerRefresh))
    }
    
    tableView?.dataSource = self
    tableView?.separatorStyle = .none
    
    tableView?.register(FlowListCell.self, forCellReuseIdentifier: FlowListCell.identifier)
    refreshFooter = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: #selector(footerRefresh))
    tableView?.mj_footer = refreshFooter
    tableView?.mj_footer.isHidden = true
    
    let footerView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 10))
    footerView.backgroundColor = GlobalConfig.BGWhiteColor
    tableView?.tableFooterView = footerView
    
    view.addSubview(tableView!)
  }
  
}
